package com.glqiang.security.exception;

import com.glqiang.enums.ResultEnum;
import com.glqiang.response.ResponseResult;
import com.glqiang.util.ServletUtils;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义认证失败处理
 *
 * @author glq1218
 */
@Component
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) {
        authException.printStackTrace();
        ResultEnum resultEnum = ResultEnum.NO_AUTHENTICATION;
        if (authException instanceof InternalAuthenticationServiceException) {
            resultEnum = ResultEnum.USER_NOT_EXIST;
        } else if (authException instanceof BadCredentialsException) {
            resultEnum = ResultEnum.USERNAME_OR_PASSWORD_ERROR;
            System.out.println(ResultEnum.USERNAME_OR_PASSWORD_ERROR.toString());
        } else if (authException instanceof InsufficientAuthenticationException) {
            resultEnum = ResultEnum.NO_LOGIN;
        }
        ServletUtils.renderString(response, resultEnum);
    }
}
